package com.aerozhonghuan.logisticsmall.modules.cart;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aerozhonghuan.foundation.base.BaseFragment;
import com.aerozhonghuan.foundation.eventbus.EventBusManager;
import com.aerozhonghuan.foundation.log.LogUtil;
import com.aerozhonghuan.logisticsmall.R;
import com.aerozhonghuan.logisticsmall.framework.DB.DBAdapter;
import com.aerozhonghuan.logisticsmall.modules.cart.beans.CbInfo;
import com.aerozhonghuan.logisticsmall.modules.cart.logic.CartInfoRequest;
import com.aerozhonghuan.logisticsmall.modules.common.MainActivity;
import com.aerozhonghuan.logisticsmall.modules.common.entity.GoodsObject;
import com.aerozhonghuan.logisticsmall.modules.common.entity.ProductImg;
import com.aerozhonghuan.logisticsmall.modules.common.event.UserInfoChangedSuccessEvent;
import com.aerozhonghuan.logisticsmall.modules.home.AddProductToGouwuche;
import com.aerozhonghuan.logisticsmall.modules.home.GoodsDetailsActivity;
import com.aerozhonghuan.logisticsmall.modules.order.OrderConfirmAcrivity;
import com.aerozhonghuan.logisticsmall.utils.CommunityTool;
import com.aerozhonghuan.logisticsmall.utils.CommunityUtils;
import com.aerozhonghuan.logisticsmall.utils.StatisticsConstant;
import com.aerozhonghuan.logisticsmall.widget.ProgressDialogIndicator;
import com.aerozhonghuan.logisticsmall.widget.TitleBarView;
import com.aerozhonghuan.oknet2.CommonCallback;
import com.aerozhonghuan.oknet2.CommonMessage;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * 描述: HomeFragment
 * 作者:zhangyonghui
 * 创建日期：2017/6/20  on 上午 11:27
 */
public class CartFragment extends BaseFragment implements View.OnClickListener {

    private static final String TAG = "HomeFragment";
    private View rootView;
    private TitleBarView titleBar;
    private ListView mListView;
    private MyAdapter mAdapter;//
    private ArrayList<GoodsObject> mGoodsObjects = new ArrayList<GoodsObject>();
    private boolean DEBUG = com.blankj.utilcode.util.AppUtils.isAppDebug();
    private TextView mGoodsPrice;
    private DBAdapter mDbAdapter;
    private RelativeLayout mCountLayout;
    private RelativeLayout mListViewLayout;
    private RelativeLayout mKonggouwucheLayout;
    private Set<GoodsObject> selectSet = new HashSet<GoodsObject>();
    private float mCountPrice;
    private ImageView mCheckBox;
    private Button mBackBtn;
    private DecimalFormat fnum;
    private boolean isEditMode;
    private GoodsObject mDeleveryFeeGoodsObject;//配送费商品
    ArrayList<GoodsObject> mCheckList = new ArrayList<GoodsObject>();
    private LayoutInflater inflater;
    View.OnClickListener rightClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!isEditMode) {
                titleBar.showRightText(getResources().getString(
                        R.string.finish));
                isEditMode = true;
            } else {
                titleBar.showRightText(getResources().getString(R.string.edit));
                isEditMode = false;
            }
            if (mAdapter != null) {
                mAdapter.notifyDataSetChanged();
            }
            StatisticsConstant.getInstance().ClickActionParams(39, 301, "");
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBusManager.register(this);
    }

    private void calcDelliveryRule() {
    }

    private void checkBill() {
        int totalPrice = 0;
        if (selectSet.size() > 0) {
            calcDelliveryRule();
            JSONArray array = new JSONArray();
            mCheckList.clear();
            if (mDeleveryFeeGoodsObject != null) {
                Log.d("community3", "配送费：" + mDeleveryFeeGoodsObject.getTitle() + "  $" + mDeleveryFeeGoodsObject.getPrice());
                mCheckList.add(mDeleveryFeeGoodsObject);
            }
            mCheckList.addAll(selectSet);
            for (GoodsObject goods : mCheckList) {
                JSONObject jsonObject = new JSONObject();
                try {
                    String pname = URLEncoder.encode(goods.getBaseName(), "utf-8");
                    int sourceId = goods.getSourceId();
                    if (sourceId == 0) {
                        sourceId = 1;
                    }
                    jsonObject.put("pvsid", goods.getPvsid());
                    jsonObject.put("number", goods.getIntoGouwucheSize());
                    jsonObject.put("price", goods.getPrice());
                    jsonObject.put("pname", pname);
                    jsonObject.put("sourceId", sourceId);
                    array.put(jsonObject);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                totalPrice += (goods.getPrice() * goods.getIntoGouwucheSize());
            }
        	/*int index = reString.lastIndexOf(",");
            String productString = reString.substring(0, index)
                    + reString.substring(index + 1, reString.length())
                    + "]";*/
            String productString = array.toString();
            final int finalTotalPrice = totalPrice;
            CartInfoRequest.cb(totalPrice, productString, getActivity(), new ProgressDialogIndicator(getActivity()), new CommonCallback<CbInfo>() {
                @Override
                public void onSuccess(CbInfo messsageBodyObject, CommonMessage commonMessage, String allResponseString) {
                    LogUtils.i(mCheckList, finalTotalPrice);
                    ActivityUtils.startActivity(new Intent(CartFragment.this.getActivity(), OrderConfirmAcrivity.class)
                            .putExtra("list", mCheckList)
                            .putExtra("billId", messsageBodyObject.billId)
                            .putExtra("totalPrice", fnum.format(finalTotalPrice / 100f)));
                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.buy_now:
                if (selectSet.size() > 0) {
                    checkBill();
                } else {
                    ToastUtils.showShort("请至少选择一件商品下单!");
                }
                break;
            case R.id.go_shopping:
                intent.setClass(getActivity(), MainActivity.class);
                intent.putExtra("tab", 0);
                startActivity(intent);
                break;
            case R.id.select_all:
                Log.d("community", "select_all=====");
                if (mGoodsObjects.size() > 0) {
                    if (selectSet.size() != mGoodsObjects.size()) {
                        for (GoodsObject product : mGoodsObjects) {
                            selectSet.add(product);
                            mCheckBox.setBackgroundResource(R.mipmap.selected);
                        }
                    } else {
                        selectSet.clear();
                        mCheckBox.setBackgroundResource(R.mipmap.unchecked_focused);
                    }
                    int productSize = 0;
                    mCountPrice = (float) 0.0;
                    for (GoodsObject product : selectSet) {
                        productSize += product.getIntoGouwucheSize();
                        mCountPrice += product.getPrice() * product.getIntoGouwucheSize();
                        Log.d("check", "check product:" + product.getIsCheck());
                    }
                    mAdapter.notifyDataSetChanged();
                    mCountPrice = mCountPrice / 100f;
                    String count = fnum.format(mCountPrice);
                    mGoodsPrice.setText(String.format("¥ %s", count));
                    updateSize(productSize);
                }
                break;
            default:
                break;
        }
    }

    class MyAdapter extends BaseAdapter {
        private RequestOptions options;
        ArrayList<GoodsObject> goodsObjects;

        MyAdapter(ArrayList<GoodsObject> goods) {
            goodsObjects = goods;
            options = new RequestOptions().placeholder(R.mipmap.ic_placehodler).error(R.mipmap.ic_placehodler);
        }

        @Override
        public int getCount() {
            return goodsObjects.size();
        }

        @Override
        public Object getItem(int position) {
            return goodsObjects.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            HolderView holderView;
            if (convertView == null) {
                convertView = LayoutInflater.from(CartFragment.this.getActivity())
                        .inflate(R.layout.shopping_item2, null);
                holderView = new HolderView();
                holderView.icon = (ImageView) convertView
                        .findViewById(R.id.icon);
                holderView.title = (TextView) convertView
                        .findViewById(R.id.title);
                holderView.price = (TextView) convertView
                        .findViewById(R.id.price);
                holderView.deleteLayout = (LinearLayout) convertView
                        .findViewById(R.id.delete_layout);
                holderView.checkBox = (CheckBox) convertView.findViewById(R.id.select_item);
                //holderView.endButton = (ImageButton) convertView.findViewById(R.id.end_icon);

                holderView.addBtn = (Button) convertView.findViewById(R.id.add_btn);
                holderView.minusBtn = (Button) convertView.findViewById(R.id.min_btn);
                holderView.productSizeView = (TextView) convertView.findViewById(R.id.buy_size_text);
                holderView.gouwucheItem = (View) convertView.findViewById(R.id.gouwuche_item);
                holderView.sizeInfo = (TextView) convertView.findViewById(R.id.size_info);
                holderView.productSizeLayout = (View) convertView.findViewById(R.id.product_size_layout);

                convertView.setTag(holderView);
            } else {
                holderView = (HolderView) convertView.getTag();
            }
            GoodsObject object = goodsObjects.get(position);
            //设置icon url并显示
            /*holderView.icon.setDefaultImageResId(R.mipmap.zhanweitu);
            holderView.icon.setErrorImageResId(R.mipmap.zhanweitu);*/
            //int mProductImgId = mDbAdapter.queryProductImgid(object.getPvsid());
            List<ProductImg> pImageList = object.getpImageList();
            int productImgId = 0;
            if (pImageList != null && pImageList.size() > 0) {
                for (ProductImg productImg : pImageList) {
                    if (productImg.is_thumbnail == 1) {
                        productImgId = productImg.imgid;
                        break;
                    } else {
                        productImgId = productImg.imgid;
                    }
                }
            }
            String imgUrl = CommunityTool.changeImageId(productImgId, true, false);
            Glide.with(CartFragment.this.getActivity()).load(imgUrl).apply(options).into(holderView.icon);

            holderView.title.setText(object.getBaseName());
            float pprice = (object.getPrice()) / 100f;
            //Log.d("community2", "productPrice===========>:"+pprice);
            //String resPrice = CommunityTool.getInstance().keepTwoDecimals(pprice);
            holderView.price.setText("￥" + pprice);
			/*holderView.originalPrice.setText("￥"+CommunityTool.getInstance().keepTwoDecimals(object.getMarker_price()));
			holderView.originalPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG|Paint.ANTI_ALIAS_FLAG);*/
            if (isEditMode) {
                holderView.deleteLayout.setVisibility(View.VISIBLE);
                //holderView.price.setPadding(0, 0, 120, 0);
                holderView.price.setVisibility(View.INVISIBLE);
                holderView.sizeInfo.setPadding(0, 0, 120, 0);
            } else {
                holderView.deleteLayout.setVisibility(View.INVISIBLE);
                //holderView.price.setPadding(0, 0, 0, 0);
                holderView.price.setVisibility(View.VISIBLE);
                holderView.sizeInfo.setPadding(0, 0, 0, 0);
            }
			/*if (object.getIntoGouwucheSize() <= 5) {
			    holderView.sizeInfo.setVisibility(View.VISIBLE);
            }else {
                holderView.sizeInfo.setVisibility(View.INVISIBLE);
            }*/
            holderView.sizeInfo.setText(object.getProductExceptionInfo());
            holderView.deleteLayout.setTag(object);
            holderView.deleteLayout.setOnClickListener(deleteListener);
            //icon click  如要改为item click，将layout添加点击事件
            holderView.gouwucheItem.setOnClickListener(itemEndIconListener);
            holderView.gouwucheItem.setTag(object);
            holderView.checkBox.setTag(object);
            //初始化checkbox值
            boolean select = selectSet.contains(object);
            Log.d(CommunityUtils.TAG, "getview select:" + select);
            holderView.checkBox.setChecked(select);
            holderView.checkBox.setOnCheckedChangeListener(checkBoxListener);

            holderView.productSizeView.setText("" + object.getIntoGouwucheSize());
            holderView.addBtn.setOnClickListener(new addAndMinusListener(select, holderView.productSizeView, object, String.valueOf(pprice)));
            holderView.minusBtn.setOnClickListener(new addAndMinusListener(select, holderView.productSizeView, object, String.valueOf(pprice)));
            if (object.getProductType() == 2) {
                holderView.addBtn.setClickable(false);
                holderView.minusBtn.setClickable(false);
            } else {
                holderView.addBtn.setClickable(true);
                holderView.minusBtn.setClickable(true);
            }
            if (object.getProductType() == 1 || object.getProductType() == 4) {
                holderView.productSizeLayout.setVisibility(View.INVISIBLE);
            } else {
                holderView.productSizeLayout.setVisibility(View.VISIBLE);
            }

            return convertView;
        }

        class HolderView {
            ImageView icon;
            TextView title;
            TextView price;
            LinearLayout deleteLayout;
            CheckBox checkBox;
            ImageButton endButton;

            Button addBtn;
            Button minusBtn;
            TextView productSizeView;
            View gouwucheItem;

            TextView sizeInfo;
            View productSizeLayout;
        }
    }

    private class addAndMinusListener implements View.OnClickListener {

        TextView showSizeView;
        int size = 1;
        GoodsObject product;
        boolean isCheck;
        String price;

        public addAndMinusListener(boolean check, TextView textView, GoodsObject object, String pri) {
            showSizeView = textView;
            product = object;
            isCheck = check;
            price = pri;
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.add_btn:
                    size = Integer.valueOf(showSizeView.getText().toString());
                    if (price.equals("0.00") && size > 0) {
                        //T.show(MainShoppingActivity.this, "亲，此活动只限购一件哦!");
                        ToastUtils.showShort("库存不足了，先买这么多吧!");
                        return;
                    }
                    if (size < 99) {
                        int vailableSize = product.getQuantityAvailable();
                        if (size < vailableSize) {
                            size++;
                            showSizeView.setText("" + size);
                            product.setIntoGouwucheSize(size);
                            mDbAdapter.open().updateGouwuche(product.getPvsid(), CommunityUtils.USER_ID, CommunityTool.saveObject(product));
                            //product.setQuantityAvailable(size);
                            if (isCheck) {
                                String size = MainActivity.getCarNum() + "";
                                if (TextUtils.isEmpty(size)) {
                                    size = "0";
                                }
                                int gouwucheCount = Integer
                                        .valueOf(size);
                                gouwucheCount++;
                                updateSize(gouwucheCount);

                                float priceC = 0;
                                for (GoodsObject go : selectSet) {
                                    priceC += go.getPrice() * go.getIntoGouwucheSize();
                                }
                                priceC = priceC / 100f;
                                String count = fnum.format(priceC);
                                mGoodsPrice.setText(String.format("¥ %s", count));
                            }
                        } else {
                            ToastUtils.showShort("亲，此商品只有" + vailableSize + "件哦!");
                        }
                    }
                    if (size == 99) {
                        ToastUtils.showShort("购买数量已达到最大值");
                    }
                    StatisticsConstant.getInstance().ClickActionParams(45, 301, String.valueOf(product.getPvsid()));
                    break;
                case R.id.min_btn:
                    size = Integer.valueOf(showSizeView.getText().toString());
                    if (size > 1) {
                        size--;
                        showSizeView.setText("" + size);
                        product.setIntoGouwucheSize(size);
                        mDbAdapter.open().updateGouwuche(product.getPvsid(), CommunityUtils.USER_ID, CommunityTool.saveObject(product));
                        //product.setQuantityAvailable(size);
                        if (isCheck) {
                            int gouwucheCount1 = MainActivity.getCarNum();
                            gouwucheCount1--;
                            updateSize(gouwucheCount1);
                            float priceC = 0;
                            for (GoodsObject go : selectSet) {
                                priceC += go.getPrice() * go.getIntoGouwucheSize();
                            }
                        /*mCountPrice -= product.getPrice();
                        String count = fnum.format(mCountPrice);*/
                            priceC = priceC / 100f;
                            String count = fnum.format(priceC);
                            mGoodsPrice.setText(String.format("¥ %s", count));
                        }
                    /*mGoodsObjects.clear();
                    mGoodsObjects.addAll(mDbAdapter.getAllData());*/
                    }
                    StatisticsConstant.getInstance().ClickActionParams(46, 301, String.valueOf(product.getPvsid()));
                    break;
                default:
                    break;
            }
        }
    }

    CompoundButton.OnCheckedChangeListener checkBoxListener = new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton v, boolean isChecked) {
            GoodsObject object = (GoodsObject) v.getTag();
            if (isChecked) {
                if (DEBUG)
                    Log.d("check", "check==true");
                selectSet.add(object);
                object.setIsCheck(0);
                mDbAdapter.open().updateGouwuche(object.getPvsid(), CommunityUtils.USER_ID, CommunityTool.saveObject(object));
                if (selectSet.size() > 0) {
                    mCheckBox.setBackgroundResource(R.mipmap.selected);
                }
            } else {
                if (DEBUG)
                    Log.d("check", "check==false");
                selectSet.remove(object);
                object.setIsCheck(1);
                mDbAdapter.open().updateGouwuche(object.getPvsid(), CommunityUtils.USER_ID, CommunityTool.saveObject(object));
                if (selectSet.size() == 0) {
                    mCheckBox.setBackgroundResource(R.mipmap.unchecked_focused);
                }
            }
            int productSize = 0;
            float price = 0.0f;
            for (GoodsObject product : selectSet) {
                productSize += product.getIntoGouwucheSize();
                price += product.getPrice() * product.getIntoGouwucheSize();
            }
            price = price / 100f;
            String dd = fnum.format(price);
            mGoodsPrice.setText(String.format("¥ %s", dd));
            mAdapter.notifyDataSetChanged();
            updateSize(productSize);
        }
    };


    View.OnClickListener itemEndIconListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            GoodsObject product = (GoodsObject) v.getTag();
            Intent intent = new Intent();
            if (product.getProductType() == 1) {
                intent.setClass(CartFragment.this.getActivity(), RunErrandsActivity.class);
                intent.putExtra("task_context", product.getProductLeaveMsg());
                intent.putExtra("businessid", product.getMin());
            } else if (product.getProductType() == 2) {
                intent.setClass(CartFragment.this.getActivity(), ExpressActivity.class);
                intent.putExtra("businessid", product.getMin());
            } else if (product.getProductType() == 4) {
                intent.setClass(CartFragment.this.getActivity(), ExpressSendActivity.class);
                intent.putExtra("businessid", product.getMin());
            } else {
                intent.setClass(CartFragment.this.getActivity(), GoodsDetailsActivity.class);
                intent.putExtra("pvsid", product.getPvsid());
            }
            startActivity(intent);
        }
    };


    private void deleteOneProduct(GoodsObject product1) {
        int size = 0;
        float priceCount = 0;
        if (DEBUG) {
            Log.d("community2", "delete product=" + product1.getPvsid());
        }
        boolean contains = false;
        for (GoodsObject goodsObject : selectSet) {
            size += goodsObject.getIntoGouwucheSize();
            priceCount += goodsObject.getPrice() * goodsObject.getIntoGouwucheSize();
            if (goodsObject.getPvsid() == product1.getPvsid()) {
                contains = true;
            }
        }
        if (DEBUG) {
            Log.d("community", "contains===" + contains);
        }
        if (contains) {
            size = size - product1.getIntoGouwucheSize();
            priceCount = priceCount - (float) (product1.getPrice() * product1.getIntoGouwucheSize());
            priceCount = priceCount / 100f;
            String dd = fnum.format(priceCount);
            mGoodsPrice.setText(String.format("¥ %s", dd));
            updateSize(size);
            selectSet.remove(product1);
        }
        mDbAdapter.deleteTitle(String.valueOf(product1.getPvsid()));
        mGoodsObjects.remove(product1);

        if (mGoodsObjects.size() == 0) {
            mListViewLayout.setVisibility(View.GONE);
            mCountLayout.setVisibility(View.GONE);
            mKonggouwucheLayout.setVisibility(View.VISIBLE);
            titleBar.setRightTextVisibility(false);
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d("community2", "MainShoppingActivity onPause()");
        String outOfStock = getResources().getString(R.string.product_outof_stock);
        for (GoodsObject product : mGoodsObjects) {
            if (product.getProductExceptionInfo().equals(outOfStock)) {
                mDbAdapter.deleteTitle(String.valueOf(product.getPvsid()));
            }
        }
    }

    private void deleteProductFormCar() {
        int size = 0;
        float priceCount = (float) 0;
        for (GoodsObject product : selectSet) {
            boolean value = mDbAdapter.deleteTitle(String.valueOf(product.getPvsid()));
            size += product.getIntoGouwucheSize();
            priceCount += product.getPrice() * product.getIntoGouwucheSize();
        }
        mGoodsObjects.clear();
        mGoodsObjects.addAll(mDbAdapter.getAllData());
        //selectSet重新添加  重置
        selectSet.clear();
        for (GoodsObject product : mGoodsObjects) {
            if (product.getIsCheck() == 0) {
                selectSet.add(product);
            }
        }
        size = 0;
        priceCount = 0;
        mCountPrice = 0;
        for (GoodsObject product : selectSet) {
            size += product.getIntoGouwucheSize();
            priceCount += product.getPrice() * product.getIntoGouwucheSize();
            mCountPrice += product.getPrice();
        }

        mAdapter.notifyDataSetChanged();
        mCountPrice = mCountPrice / 100f;
        String dd = fnum.format(mCountPrice);
        mGoodsPrice.setText(String.format("¥ %s", dd));

        if (mGoodsObjects.size() == 0) {
            mListViewLayout.setVisibility(View.GONE);
            mCountLayout.setVisibility(View.GONE);
            mKonggouwucheLayout.setVisibility(View.VISIBLE);
            titleBar.setRightTextVisibility(false);
        }
        updateSize(size);
    }

    View.OnClickListener deleteListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            GoodsObject product = (GoodsObject) v.getTag();
            deleteOneProduct(product);
            if (mAdapter != null) {
                mAdapter.notifyDataSetChanged();
            }
            StatisticsConstant.getInstance().ClickActionParams(40, 301, String.valueOf(product.getPvsid()));
        }
    };


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_cart, null);
            initView();
            initData();
        }
        return rootView;
    }

    private void initView() {
        inflater = LayoutInflater.from(getContext());
        titleBar = (TitleBarView) rootView.findViewById(R.id.titlebarview1);
        titleBar.enableBackButton(false);
        titleBar.setTitle(getResources().getString(R.string.string_tab_cart));
        titleBar.showRightText(getResources().getString(R.string.edit), rightClick);
        mDbAdapter = new DBAdapter(getActivity());
        fnum = new DecimalFormat("##0.00");
        mCheckBox = (ImageView) rootView.findViewById(R.id.select_all);
        mListView = (ListView) rootView.findViewById(R.id.select_list);
        mListView.addFooterView(inflater.inflate(R.layout.view_footer_list, null));
        mGoodsPrice = (TextView) rootView.findViewById(R.id.goods_price);
        Button buyNow = (Button) rootView.findViewById(R.id.buy_now);
        buyNow.setOnClickListener(this);
        mCheckBox.setOnClickListener(this);
        /*mFunctionButton = (Button) rootView.findViewById(R.id.function);
        mFunctionButton.setText(getResources().getString(R.string.edit));
        mFunctionButton.setOnClickListener(this);*/
        Button goShoppingBtn = (Button) rootView.findViewById(R.id.go_shopping);
//        goShoppingBtn.setOnClickListener(this);
        mCountLayout = (RelativeLayout) rootView.findViewById(R.id.count_layout);
        mListViewLayout = (RelativeLayout) rootView.findViewById(R.id.listview_layout);
        mKonggouwucheLayout = (RelativeLayout) rootView.findViewById(R.id.konggouwuche_layout);
    }

    private void initData() {
        mGoodsObjects.clear();
        mGoodsObjects.addAll(mDbAdapter.getAllData());
        selectSet.clear();
        int productSize = 0;
        mCountPrice = (float) 0;
        for (GoodsObject product : mGoodsObjects) {
            if (product.getIsCheck() == 0) {
                productSize += product.getIntoGouwucheSize();
                mCountPrice += product.getPrice() * product.getIntoGouwucheSize();
                selectSet.add(product);
            }
        }
        if (selectSet.size() > 0) {
            mCheckBox.setBackgroundResource(R.mipmap.selected);
        } else {
            mCheckBox.setBackgroundResource(R.mipmap.unchecked_focused);
        }

        if (mGoodsObjects.size() > 0) {
            titleBar.setRightTextVisibility(true);
            mListViewLayout.setVisibility(View.VISIBLE);
            mCountLayout.setVisibility(View.VISIBLE);
            mKonggouwucheLayout.setVisibility(View.GONE);
        } else {
            titleBar.setRightTextVisibility(false);
            mListViewLayout.setVisibility(View.GONE);
            mCountLayout.setVisibility(View.GONE);
            mKonggouwucheLayout.setVisibility(View.VISIBLE);
        }
        if (mAdapter == null) {
            mAdapter = new MyAdapter(mGoodsObjects);
            mListView.setAdapter(mAdapter);
        }
        mAdapter.notifyDataSetChanged();
        mCountPrice = mCountPrice / 100;
        String dd = fnum.format(mCountPrice);
        mGoodsPrice.setText(String.format("¥ %s", dd));
        updateSize(productSize);

    }

    private void updateSize(int productsize) {
		/*int activitySize = MyApplication.getInstance().getActivitys().size();
		for (int i = 0; i < activitySize; i++) {
			AddProductToGouwuche in = (AddProductToGouwuche) MyApplication.getInstance().getActivitys().get(i);
			in.updateData(productsize);
		}*/
        AddProductToGouwuche in = MainActivity.sMainActivity;
        in.updateData(productsize);
    }


    @Override
    public void onDestroy() {
        EventBusManager.unregister(this);
        super.onDestroy();
    }

    @Override
    public void onStart() {
        super.onStart();
    }


    /**
     * 显示隐藏fragment时控制轮播
     *
     * @param hidden
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {

        } else {
            initData();
        }
    }


    /**
     * 用户信息发生改变
     *
     * @param e
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    @SuppressWarnings("unused")
    public void onEvent(UserInfoChangedSuccessEvent e) {
        if (getActivity() == null || getActivity().isFinishing())
            return;
        LogUtil.d(TAG, "收到事件: 用户信息发生改变");

    }
}
